<template>
  <!-- 外层容器处理用户设置的旋转角度 -->
  <div class="w-image-wrapper" :style="wrapperStyle">
    <!-- 内层元素处理动画 -->
    <div 
      class="w-image animated animate__animated"
      :class="imageClass"
      :style="contentStyle"
      @mousedown="handleMousedown"
      @touchstart="handleTouchstart"
      :data-delay="delay" 
      :data-show="showClass" 
      :data-emphasis="emphasisClass" 
      :data-out="outClass"
      :data-emphasis-delay="emphasisDelay" 
      :data-out-delay="outDelay"
    ></div>
  </div>
</template>

<script>
import element from '@/mixins/element'

export default {
    props: {
        img: {
            type: String
        },
        // 动画相关属性
        delay: {
            type: [Number, String],
            default: 0
        },
        showClass: {
            type: String,
            default: ''
        },
        emphasisClass: {
            type: String,
            default: ''
        },
        outClass: {
            type: String,
            default: ''
        },
        emphasisDelay: {
            type: [Number, String],
            default: 1000
        },
        outDelay: {
            type: [Number, String],
            default: 28000
        }
    },
    name: 'w-image',
    mixins: [element],
    data() {
        return {
            isLoaded: false,
            hasError: false,
            retryCount: 0,
            maxRetries: 3
        }
    },
    computed: {
        imageClass() {
            return {
                'loaded': this.isLoaded,
                'error': this.hasError,
                'loading': !this.isLoaded && !this.hasError
            }
        },
        wrapperStyle() {
            // 外层容器只处理旋转角度
            const { angel = 0, width = 0, height = 0, top = 0, left = 0, zIndex = 1 } = this.styleObj;
            const style = {
                transform: `rotateZ(${angel}deg)`,
                transformOrigin: 'center center',
                position: 'absolute',
                width: `${this.calcXAttr(width)}px`,
                height: `${this.calcYAttr(height)}px`,
                top: `${this.calcYAttr(top)}px`,
                left: `${this.calcXAttr(left)}px`,
                zIndex: zIndex
            };
            
            return style;
        },
        contentStyle() {
            // 内层元素处理除旋转外的其他样式
            const { 
                radius = 0, 
                color = '#FFF', 
                animationCount = '1' 
            } = this.styleObj;
            
            const style = {
                color,
                width: '100%',
                height: '100%',
                borderRadius: `${radius}px`,
                'animation-iteration-count': `${animationCount}`,
                backgroundSize: '100% 100%',
                backgroundRepeat: 'no-repeat'
            };
            
            // 只有在图片加载成功时才设置backgroundImage
            if (this.isLoaded && this.img) {
                style.backgroundImage = `url(${this.img})`;
            }
            
            return style;
        }
    },
    watch: {
        img: {
            handler(newImg) {
                if (newImg) {
                    this.loadImage(newImg);
                }
            },
            immediate: true
        }
    },
    methods: {
        handleMousedown(e) {
            this.$emit('mousedown', e)
        },
        handleTouchstart(e) {
            this.$emit('touchstart', e)
        },
        loadImage(src) {
            // 重置状态
            this.isLoaded = false;
            this.hasError = false;
            
            // 如果是Base64格式或URL的图片，加载它
            if (src && (src.startsWith('data:image') || src.startsWith('http') || src.startsWith('/'))) {
                this.doLoadImage(src);
            } else {
                // 对于非图片URL，直接标记为已加载
                this.isLoaded = true;
            }
        },
        doLoadImage(src) {
            const image = new Image();
            
            image.onload = () => {
                console.log('图片加载成功:', src);
                this.isLoaded = true;
                this.retryCount = 0; // 重置重试计数
            };
            
            image.onerror = () => {
                console.error('图片加载出错:', src);
                // 如果还有重试次数，尝试重试
                if (this.retryCount < this.maxRetries) {
                    this.retryCount++;
                    console.warn(`图片加载失败，正在重试 (${this.retryCount}/${this.maxRetries}):`, src);
                    
                    // 延迟重试
                    setTimeout(() => {
                        this.doLoadImage(src);
                    }, 1000 * this.retryCount); // 递增延迟
                } else {
                    // 达到最大重试次数，标记为错误
                    this.hasError = true;
                    this.retryCount = 0;
                    console.error('图片加载失败，已达到最大重试次数:', src);
                }
            };
            
            image.src = src;
        }
    }
}
</script>

<style lang="scss" scoped>
.w-image-wrapper {
    transform-origin: center center;
}

.w-image {
    display: block;
    outline: none;
    user-select: none;
    transform-origin: center center;
    cursor: move;
    
    /* 添加加载状态样式 */
    background-color: #f5f5f5;
    
    /* 加载中的动画效果 */
    &.loading::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: loading 1.5s infinite;
    }
    
    /* 加载完成后隐藏占位符 */
    &.loaded::before {
        display: none;
    }
    
    /* 加载失败时的样式 */
    &.error {
        background-color: #ffebee;
        &::after {
            content: '图片加载失败';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #f44336;
            font-size: 12px;
        }
    }
    
    /* 默认背景色 */
    &.loaded {
        background-color: transparent;
    }
}

@keyframes loading {
    0% {
        background-position: 200% 0;
    }
    100% {
        background-position: -200% 0;
    }
}
</style>